import java.util.ArrayList;
import java.util.HashMap;

/*This class is used to help determine which machine to forward requests to*/

public class FingerTable {

	public HashMap<Integer, MachineData> table = new HashMap<Integer, MachineData>();
	public ArrayList<Integer> tableList;
	public ArrayList<MachineData> machines;
	public int index;
	public int N;
	
	public FingerTable(ArrayList<MachineData> machines, int index) {

		int tableSize = (int) (Math.log(machines.size())/Math.log(2));
		N = machines.size();

		for(int i = 1; i <= tableSize; i++) { //fill table
			int next = index + (int) (Math.pow(2,i-1));
			next = next % N;
			table.put(next, machines.get(next));
		}

		this.tableList = new ArrayList<Integer>(table.keySet());
		this.machines = machines;
		this.index = index;
	}

	public int get(int key) { //obtain node to forward request to from the key given

		key = key % N;
		
		int max = -1;

		//choose largest entry <= key
		for(Integer i: tableList) {
			if( i <= key && i > max) {
				max = i;
			}
		}

		//choose largest key
		if(max == -1) {
			for(Integer i: tableList) {
				if(i > max) {
					max = i;
				}
			}
		}

		return max;
	}
}
